//
//  XSJRegisterVC.m
//  XSJ
//
//  Created by yuanyuan he on 2020/5/7.
//  Copyright © 2020 apple. All rights reserved.
//

#import "XSJRegisterVC.h"
#import "SVProgressHUD.h"
#import "MJExtension.h"
#import "CQCountDownButton.h"
#import "UserInfoModel.h"
#import "JXLayoutButton.h"
#import "http_user.h"
#import "XSJTool.h"
#import "XSJLoginVC.h"

@interface XSJRegisterVC ()

@property (nonatomic, strong) UIImageView* icon1View;
@property (nonatomic, strong) UIImageView* icon2View;
@property (nonatomic, strong) UIImageView* icon3View;
@property (nonatomic, strong) UIImageView* icon4View;

@property (nonatomic, strong) UITextField *phoneTextField;
@property (nonatomic, strong) UITextField *vcodeTextField;
@property (nonatomic, strong) UITextField *invitationTextField;

@property (nonatomic, strong) CQCountDownButton* vcodeButton;

@property (nonatomic, strong) UIView* line1View;
@property (nonatomic, strong) UIView* line2View;
@property (nonatomic, strong) UIView* line3View;

@property (nonatomic, strong) UIButton *registerButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *privacyButton;

@end

@implementation XSJRegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    [ZFTool isHiddenNavigationBarSeparatorLine:YES vc:self];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
    
    //点击隐藏键盘
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];[self.view addGestureRecognizer:singleTap];
    [self setRightBarButton];
}

-(void)setRightBarButton
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(okButtonDidClick)];
    [self.navigationItem.rightBarButtonItem setTintColor:ColorHex(0x0D0202)];
}

-(void)okButtonDidClick
{
    //登录
    XSJLoginVC* vc = [[XSJLoginVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    [self.view endEditing:YES];
}


- (void)setupUI
{
    [self.view addSubview:self.icon1View];
    [self.view addSubview:self.icon2View];
    [self.view addSubview:self.icon3View];
    [self.view addSubview:self.icon4View];
    [self.view addSubview:self.line1View];
    [self.view addSubview:self.line2View];
    [self.view addSubview:self.line3View];
    [self.view addSubview:self.phoneTextField];
    [self.view addSubview:self.vcodeTextField];
    [self.view addSubview:self.invitationTextField];
    [self.view addSubview:self.vcodeButton];
    [self.view addSubview:self.registerButton];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.privacyButton];
    
    [_icon1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.centerX.mas_equalTo(self.view);
    }];
    
    [_icon2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(65);
        make.top.equalTo(self->_icon1View.mas_bottom).offset(66);
        make.width.height.mas_equalTo(20);
    }];
    
    [_icon3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(65);
        make.top.equalTo(self->_icon2View.mas_bottom).offset(35);
        make.width.height.mas_equalTo(20);
    }];
    
    [_icon4View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(65);
        make.top.equalTo(self->_icon3View.mas_bottom).offset(35);
        make.width.height.mas_equalTo(20);
    }];
    
    [_phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_icon2View.mas_right).offset(15);
        make.top.bottom.equalTo(self->_icon2View);
        make.right.mas_equalTo(-15);
    }];
    
    [_vcodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_icon3View.mas_right).offset(10);
        make.top.bottom.equalTo(self->_icon3View);
        make.right.mas_equalTo(-100);
    }];
    
    [_invitationTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_icon4View.mas_right).offset(10);
        make.top.bottom.equalTo(self->_icon4View);
        make.right.mas_equalTo(-15);
    }];
    
    [_vcodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->_line1View.mas_bottom).offset(17);
        make.right.mas_equalTo(-52);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(30);
    }];
    
    [_line1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(271);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self->_icon2View.mas_bottom).offset(10);
        make.height.mas_equalTo(1);
    }];
    
    [_line2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(271);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self->_icon3View.mas_bottom).offset(10);
        make.height.mas_equalTo(1);
    }];
    
    [_line3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(271);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self->_icon4View.mas_bottom).offset(10);
        make.height.mas_equalTo(1);
    }];
    
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(285);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self->_line3View.mas_bottom).offset(10);
    }];
    
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       make.right.equalTo(self->_privacyButton.mas_left);
       make.centerY.equalTo(_privacyButton);
    }];
    
    [_privacyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_bottom).offset(-70);
        make.right.mas_equalTo(-93);
    }];
}

//用户注册协议钮被点击
-(void)privacyButtonDidClick
{
    //[JumpVCTool to_WebVC:@"http://kn1.knwlapp.com/mobile/article/detail/id/3.html" title:@"隐私协议" naviVC:self.navigationController];
}

- (UIImageView *)icon1View {
    if (_icon1View == nil) {
        _icon1View = [[UIImageView alloc] init];
        _icon1View.image = [UIImage imageNamed:@"New03"];
    }
    return _icon1View;
}

- (UIImageView *)icon2View {
    if (_icon2View == nil) {
        _icon2View = [[UIImageView alloc] init];
        _icon2View.image = [UIImage imageNamed:@"Phone"];
    }
    return _icon2View;
}

- (UIImageView *)icon3View {
    if (_icon3View == nil) {
        _icon3View = [[UIImageView alloc] init];
        _icon3View.image = [UIImage imageNamed:@"Verification"];
    }
    return _icon3View;
}

- (UIImageView *)icon4View {
    if (_icon4View == nil) {
        _icon4View = [[UIImageView alloc] init];
        _icon4View.image = [UIImage imageNamed:@"Password"];
    }
    return _icon4View;
}

- (UITextField *)phoneTextField {
    if (_phoneTextField == nil) {
        _phoneTextField = [[UITextField alloc] init];
        _phoneTextField.placeholder = @"请输入手机号码";
        _phoneTextField.font = [UIFont systemFontOfSize:12];
        _phoneTextField.textColor = ColorHex(0x222222);
        // 重点
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入手机号码" attributes:
                                          @{NSForegroundColorAttributeName:ColorHex(0x999999),
                                            NSFontAttributeName:_phoneTextField.font
                                            }];
        _phoneTextField.attributedPlaceholder = attrString;
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        //改变删除的图标
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIButton *button =[_phoneTextField valueForKey:@"_clearButton"];
        [button setImage:[UIImage imageNamed:@"shangdiao"] forState:UIControlStateNormal];
    }
    return _phoneTextField;
}

- (UITextField *)vcodeTextField {
    if (_vcodeTextField == nil) {
        _vcodeTextField = [[UITextField alloc] init];
        _vcodeTextField.placeholder = @"请输入验证码";
        _vcodeTextField.font = [UIFont systemFontOfSize:12];
        _vcodeTextField.textColor = ColorHex(0x222222);
        // 重点
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:
                                          @{NSForegroundColorAttributeName:ColorHex(0x999999),
                                            NSFontAttributeName:_phoneTextField.font
                                            }];
        _vcodeTextField.attributedPlaceholder = attrString;
        _vcodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _vcodeTextField.keyboardType = UIKeyboardTypeNumberPad;
        //改变删除的图标
        _vcodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIButton *button =[_vcodeTextField valueForKey:@"_clearButton"];
        [button setImage:[UIImage imageNamed:@"shangdiao"] forState:UIControlStateNormal];
        
    }
    return _vcodeTextField;
}

- (UITextField *)invitationTextField {
    if (_invitationTextField == nil) {
        _invitationTextField = [[UITextField alloc] init];
        _invitationTextField.placeholder = @"请输入邀请码（可不填）";
        _invitationTextField.font = [UIFont systemFontOfSize:12];
        _invitationTextField.textColor = ColorHex(0x222222);
        // 重点
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入邀请码（可不填）" attributes:
                                          @{NSForegroundColorAttributeName:ColorHex(0x999999),
                                            NSFontAttributeName:_phoneTextField.font
                                            }];
        _invitationTextField.attributedPlaceholder = attrString;
        _invitationTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _invitationTextField.keyboardType = UIKeyboardTypeNumberPad;
        //改变删除的图标
        _invitationTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIButton *button =[_invitationTextField valueForKey:@"_clearButton"];
        [button setImage:[UIImage imageNamed:@"shangdiao"] forState:UIControlStateNormal];
        
    }
    return _invitationTextField;
}

- (UIButton *)registerButton {
    if (_registerButton == nil) {
        _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _registerButton.backgroundColor = ColorHex(0xffffff);
        [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
        [_registerButton setBackgroundImage:[UIImage imageNamed:@"Sign2"] forState:UIControlStateNormal];
        _registerButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_registerButton addTarget:self action:@selector(registerButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}

- (UIView *)line1View {
    if (_line1View == nil) {
        _line1View = [[UIView alloc] init];
        _line1View.backgroundColor = ColorHex(0xC1C1C1);
    }
    return _line1View;
}

- (UIView *)line2View {
    if (_line2View == nil) {
        _line2View = [[UIView alloc] init];
        _line2View.backgroundColor = ColorHex(0xC1C1C1);
    }
    return _line2View;
}

- (UIView *)line3View {
    if (_line3View == nil) {
        _line3View = [[UIView alloc] init];
        _line3View.backgroundColor = ColorHex(0xC1C1C1);
    }
    return _line3View;
}

- (UILabel *)titleLabel {
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = ColorHex(0x000000);
        _titleLabel.font = [UIFont systemFontOfSize:12];
        _titleLabel.text = @"我已阅读并同意";
    }
    return _titleLabel;
}

- (UIButton *)privacyButton {
    if (_privacyButton == nil) {
        _privacyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_privacyButton setTitle:@"《用户注册协议》" forState:UIControlStateNormal];
        [_privacyButton setTitleColor:ColorHex(0x3169EB) forState:UIControlStateNormal];
        _privacyButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_privacyButton addTarget:self action:@selector(privacyButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _privacyButton;
}

- (void)vcodeButtonDidClick
{
    NSString* phone = _phoneTextField.text;

    ZWeakSelf
    [http_user sendCode:phone type:@"register" success:^(id responseObject)
     {
         [weakSelf verifycode_ok:responseObject];

     } failure:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:error.domain];
     }];
}

-(void)verifycode_ok:(id)responseObject
{
    [SVProgressHUD showSuccessWithStatus:@"发送成功"];
    
}

- (CQCountDownButton *)vcodeButton
{
    if (_vcodeButton == nil) {
        _vcodeButton = [CQCountDownButton buttonWithType:UIButtonTypeCustom];
        [_vcodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _vcodeButton.backgroundColor = ColorHex(0xffffff);
        [_vcodeButton setTitleColor:ColorHex(0xCC88F0) forState:UIControlStateNormal];
        _vcodeButton.titleLabel.font = [UIFont systemFontOfSize:12];
        _vcodeButton.layer.borderWidth = 1.0f;
        _vcodeButton.layer.borderColor = ColorHex(0xCC88F0).CGColor;
        _vcodeButton.layer.cornerRadius = 5.0f;
        _vcodeButton.clipsToBounds = YES;
        //        [_vcodeButton addTarget:self action:@selector(vcodeButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
        __weak typeof(self) weakSelf = self;
        [_vcodeButton configDuration:60 buttonClicked:^{
            //========== 按钮点击 ==========//
            if ( kStringIsEmpty(weakSelf.phoneTextField.text) )
            {
                [SVProgressHUD showInfoWithStatus:@"请输入手机号码"];
                weakSelf.vcodeButton.enabled = YES;
                return;
            }

            if ( [XSJTool isPhoneNumber:weakSelf.phoneTextField.text]==NO )
            {
                [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
                weakSelf.vcodeButton.enabled = YES;
                return;
            }

            [weakSelf.vcodeButton startCountDown];
            [weakSelf vcodeButtonDidClick];
        } countDownStart:^{
            //========== 倒计时开始 ==========//
            NSLog(@"倒计时开始");
        } countDownUnderway:^(NSInteger restCountDownNum) {
            //========== 倒计时进行中 ==========//
            NSString *title = [NSString stringWithFormat:@"%ldS", restCountDownNum];
            [weakSelf.vcodeButton setTitle:title forState:UIControlStateNormal];
        } countDownCompletion:^{
            //========== 倒计时结束 ==========//
            [weakSelf.vcodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            NSLog(@"倒计时结束");
        }];
    }
    return _vcodeButton;
}

//注册钮被点击
- (void)registerButtonDidClick
{
    NSString* phone = _phoneTextField.text;
    NSString* code = _vcodeTextField.text;
    
    if (kStringIsEmpty(phone))
    {
        [SVProgressHUD showInfoWithStatus:@"请输入手机号"];
        return;
    }
    
    if ( [XSJTool isPhoneNumber:phone]==NO )
    {
        [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
        return;
    }

    if (kStringIsEmpty(code))
    {
        [SVProgressHUD showInfoWithStatus:@"请输入验证码"];
        return;
    }

    [self toLogin:@"123" phone:phone verify_code:code];
}


//登录
-(void)toLogin:(NSString*)nick_name phone:(NSString*)phone verify_code:(NSString*)verify_code
{
    ZWeakSelf
    [SVProgressHUD showWithStatus:@"正在登录"];
    [http_user simple_register:nick_name phone:phone verify_code:verify_code invite_code:@"200" success:^(id responseObject)
     {
         [SVProgressHUD showSuccessWithStatus:@"注册成功"];
         [weakSelf toLogin_ok:responseObject];
     } failure:^(NSError *error) {
         [SVProgressHUD showInfoWithStatus:error.domain];
         if (error.code==500008)
         {
             [weakSelf.navigationController popViewControllerAnimated:YES];
         }
     }];
}

-(void)toLogin_ok:(id)responseObject
{
    if(kObjectIsEmpty(responseObject))
    {
        return;
    }
    
    UserInfoModel* userInfo = nil;
    NSDictionary* dict = [responseObject objectForKey:@"loginPlateUser"];
    if (!kObjectIsEmpty(dict))
    {
        userInfo = [UserInfoModel mj_objectWithKeyValues:responseObject];
    }
    
    NSString* token = [responseObject objectForKey:@"token"];
    if (!kStringIsEmpty(token))
    {
        userInfo.token = token;
    }
    
    [userInfo saveUserInfo];
    //登录成功通知
    [[NSNotificationCenter defaultCenter] postNotificationName:UserLoginRegisterNotification object:self];
//
//    //登录网易云
//    [[[NIMSDK sharedSDK] loginManager] login:userInfo.ID token:userInfo.chatToken completion:^(NSError * _Nullable error) {
//
//        if (!error)
//        {
//            // 登录成功跳转
//            DLog(@"登录网易云成功");
//        } else
//        {
//            DLog(@"登录网易云失败:%@", error.domain);
//            // 登录失败跳转
//        }
//    }];
}


@end
